#!/usr/bin/env python3
import asyncio
import websockets
import logging
import json
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def handler(websocket, path):
    """简化的WebSocket处理器"""
    client_address = websocket.remote_address
    logger.info(f"新客户端连接: {client_address}")
    
    try:
        async for message in websocket:
            logger.info(f"收到消息: {message}")
            
            # 简单的回显响应
            try:
                response = f"服务器收到: {message}"
                await websocket.send(response)
                logger.info(f"发送响应: {response}")
            except Exception as e:
                logger.error(f"发送响应失败: {e}")
                
    except websockets.exceptions.ConnectionClosed:
        logger.info(f"客户端断开连接: {client_address}")
    except Exception as e:
        logger.error(f"处理连接时出错: {e}")
    finally:
        logger.info(f"连接结束: {client_address}")

async def main():
    host = "0.0.0.0"
    port = 8080
    logger.info(f"启动WebSocket服务器: ws://{host}:{port}")
    
    try:
        # 使用最简单的服务器配置
        server = await websockets.serve(handler, host, port)
        logger.info("WebSocket服务器启动成功")
        
        # 保持服务器运行
        await asyncio.Future()
        
    except Exception as e:
        logger.error(f"服务器启动失败: {e}")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("服务器停止")
    except Exception as e:
        logger.error(f"服务器运行出错: {e}") 